<template>
    <div>
        <CardBox v-for="(item, index) in cardList" :key="item.id" :title="`巡查点${index + 1}`" style="padding-bottom: 32px">
            <BaseButton v-if="cardList.length > 1" slot="button" type="text" color="danger" icon="el-icon-delete" @click="handleDelete(index)">
                删除
            </BaseButton>
            <el-form ref="form" :model="item" :rules="rules" size="medium" label-width="96px">
                <el-row :gutter="24">
                    <el-col :xl="6" :lg="8">
                        <el-form-item label="方向" prop="direction">
                            <el-select v-model="item.direction" placeholder="请选择" style="width: 100%" clearable>
                                <el-option v-for="m in DirectionTwoWayOptions" :key="m.value" :label="m.label" :value="m.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xl="12" :lg="16">
                        <el-col :span="7" style="padding: 0">
                            <el-form-item label="构造物桩号" prop="startStake1">
                                <el-input v-model.trim="item.startStake1" placeholder="请输入" maxlength="3">
                                    <div slot="prepend" class="input-unit">K</div>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5" style="padding: 0">
                            <el-form-item class="spe-item" label-width="30px" label="+" prop="endStake1">
                                <el-input v-model.trim="item.endStake1" maxlength="3" placeholder="请输入" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="7" style="padding: 0">
                            <el-form-item class="spe-item" label-width="50px" label="~" prop="startStake2">
                                <el-input v-model.trim="item.startStake2" placeholder="请输入" maxlength="3">
                                    <div slot="prepend" class="input-unit">K</div>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5" style="padding: 0">
                            <el-form-item class="spe-item" label-width="30px" label="+" prop="endStake2">
                                <el-input v-model.trim="item.endStake2" maxlength="3" placeholder="请输入" />
                            </el-form-item>
                        </el-col>
                    </el-col>
                    <el-col :xl="6" :lg="8">
                        <el-form-item label="构造物名称" prop="name">
                            <el-input v-model.trim="item.name" maxlength="20" show-word-limit placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xl="6" :lg="8">
                        <el-form-item label="本期检查" prop="currentCheckDate">
                            <el-date-picker
                                v-model="item.currentCheckDate"
                                type="date"
                                placeholder="请选择"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"
                                style="width: 100%"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :xl="6" :lg="8">
                        <el-form-item label="上期检查" prop="lastCheckDate">
                            <el-date-picker
                                v-model="item.lastCheckDate"
                                type="date"
                                placeholder="请选择"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"
                                style="width: 100%"
                            />
                        </el-form-item>
                    </el-col>
                    
                    <el-col :span="24">
                        <el-form-item label="上传图片">
                            <ImageUpload ref="imageUpload" :list="item.photos" :limit="100"></ImageUpload>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <!-- 缺陷表格 -->
            <FlawTable ref="culvertBridgeTable"></FlawTable>
        </CardBox>

        <div class="add-btn" @click="handleAdd">添加巡查点</div>
    </div>
</template>

<script>
import { uniqueId } from 'lodash-es'
import reconfirm from '@/utils/reconfirm'
import FlawTable from './FlawTable.vue'
import { isInteger } from '@/utils/validate'
import { DirectionTwoWayOptions } from '@/config/constants'

export default {
    name: 'CulvertCardList',
    components: {
        FlawTable
    },
    data() {
        return {
            DirectionTwoWayOptions,
            cardList: [{ fid: uniqueId() }],
            form: {},
            rules: {
                direction: [{ required: true, message: '请选择方向', trigger: 'change' }],
                name: [{ required: true, message: '请输入名称', trigger: 'change' }],
                // lastCheckDate: [{ required: true, message: '请选择上期检查日期', trigger: 'change' }],
                currentCheckDate: [{ required: true, message: '请选择本期检查日期', trigger: 'change' }],
                startStake1: [
                    { required: true, message: '请输入起点桩号', trigger: 'blur' },
                    { required: true, validator: this.validNum, trigger: 'blur' }
                ],
                endStake1: [{ required: true, message: '请输入起点桩号', trigger: 'blur' }],
                startStake2: [
                    { required: true, message: '请输入终点桩号', trigger: 'blur' },
                    { required: true, validator: this.validNum, trigger: 'blur' }
                ],
                endStake2: [{ required: true, message: '请输入终点桩号', trigger: 'blur' }]
            }
        }
    },
    methods: {
        handleDelete(index) {
            reconfirm({
                isPromise: false,
                callback: () => {
                    this.cardList.splice(index, 1)
                }
            })
        },
        handleValidate() {
            return new Promise((resolve, reject) => {
                const tableListValidateRes = this.tableListValidate()
                if (tableListValidateRes) {
                    this.$message.error('异常描述（性质、范围、程度）不能为空！')
                    resolve(false)
                    return
                }
                const list = []
                const validas = []
                this.$refs['form'].forEach((item, index) => {
                    list.push(
                        new Promise((resolve) => {
                            item.validate((valida) => {
                                validas.push(valida)
                                resolve()
                            })
                        })
                    )
                })
                Promise.all([...list])
                    .then(() => {
                        const res = !validas.some((item) => item === false)
                        resolve(res)
                    })
                    .catch((err) => {
                        reject(err)
                    })
            })
        },
        handleAdd() {
            this.cardList.push({ fid: uniqueId() })
            console.log(this.cardList)
        },
        tableListValidate() {
            const list = []
            this.$refs.culvertBridgeTable.forEach((item) => {
                item.tableList.forEach((item) => {
                    const hasValue = Object.values(item).some((m) => {
                        if (Array.isArray(m)) {
                            if (m.length > 0) {
                                return true
                            } else {
                                return false
                            }
                        } else if (Object.prototype.toString.call(m) === '[object Object]') {
                            if (Object.keys.length > 0) {
                                return true
                            } else {
                                return false
                            }
                        } else {
                            return !!m
                        }
                    })
                    if (hasValue) {
                        if (item.description) {
                            list.push(true)
                        } else {
                            list.push(false)
                        }
                    } else {
                        list.push(true)
                    }
                })
            })
            const res = list.some((item) => item === false)
            return res
        },
        getData() {
            this.$refs.imageUpload.forEach((item, index) => {
                this.cardList[index].photos = item.imgList.map((item) => item.response?.data?.objectUrl).toString()
            })
            this.$refs.culvertBridgeTable.forEach((item, index) => {
                this.cardList[index].content = item.tableList
            })
            this.cardList.forEach((item) => {
                item.stake = `K${item.startStake1}+${item.endStake1}~K${item.startStake2}+${item.endStake2}`
            })
            return this.cardList
        },
        validNum(rule, value, callback) {
            if (value && !isInteger(value)) {
                callback(new Error('请输入数字'))
            } else {
                callback()
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.spe-item {
    ::v-deep {
        .el-form-item__label {
            text-align: center;
            padding: 0;
            &::before {
                display: none;
            }
        }
        .el-input,
        .el-input__inner {
            min-width: auto !important;
        }
    }
}

.add-btn {
    width: 100%;
    height: 64px;
    margin-top: 32px;
    background-color: #fff;
    border: 2px dotted rgb(217, 217, 217);
    border-radius: 5px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>
